<template>
  <div class="tenant-wrapper" v-loading="loading">
    <div class="tenant-body">
      <section class="tenant-top">
        <div class='top_left'>
          <span class="left1">
            <search-input
              :defaultValue='inputValue'
              @change='handleNameSearch'
              maxWidth='200px'
              placeholder='请输入租户名称'
              class='search-input'>
            </search-input>
          </span>
        </div>
        <div class="right1">
          <type-button
            size='small'
            type='add'
            @handleClick="addTenant()">
          </type-button>
        </div>
      </section>
      <div class="table-wrapper">
        <section>
          <el-table
            :data="tenantList"
            tooltip-effect='light'
            style="width: 100%">
            <el-table-column
              type="index"
              label="序号"
              width="80">
            </el-table-column>
            <el-table-column show-overflow-tooltip
                              prop="tenantName"
                              min-width='160'
                              label="企业/团队">
            </el-table-column>
            <el-table-column show-overflow-tooltip
                              prop="registerPhone"
                              min-width='140'
                              label="主账号">
            </el-table-column>
            <el-table-column show-overflow-tooltip
                              prop="createTime"
                              min-width='140'
                              label="注册时间">
            </el-table-column>
            <el-table-column prop="isEnabled"
                              min-width='100'
                              label="状态">
              <template slot-scope="scope">
                {{!scope.row.isEnabled ? '禁用' : '启用'}}
              </template>
            </el-table-column>
            <el-table-column fixed="right"
                              label="操作"
                              width='160px'>
              <template slot-scope="scope">
                <span class='caozuo' @click='toggleUse(scope.row)'>{{scope.row.isEnabled ? '禁用' : '启用'}}</span>
                <span class="caozuo" @click="handleEdit(scope.row)">修改</span>
                <span class="caozuo" @click="handleDelete(scope.row)">删除</span>
              </template>
            </el-table-column>
          </el-table>
        </section>
        <el-pagination
          style="width:100%;text-align:center;"
          background
          v-show='tenantList.length'
          :total="total"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="pageSizesG"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="sizes, prev, pager, next">
        </el-pagination>
      </div>
    </div>
    <!-- 新增/编辑租户 -->
    <el-dialog
      class="tenant-info-wrapper"
      width="540px"
      :title='mode === "create" ? "添加租户" : "编辑租户"'
      :visible.sync="isShowTenantDialog"
      :close-on-click-modal="false"
      @close="clearTenantFields">
      <div>
        <el-form
          :model="tenantInfo"
          :rules="tenantRules"
          ref="tenantRef"
          label-width="64px"
          class="demo-ruleForm">
          <el-form-item
            label="团队"
            prop="tenantName">
            <el-input
              v-model.trim="tenantInfo.tenantName"
              maxlength="30"
              show-word-limit
              placeholder="请输入团队（企业）名称">
            </el-input>
          </el-form-item>
          <el-form-item
            label="编码"
            prop="tenantCode">
            <el-input
              :disabled="mode !== 'create'"
              placeholder="请输入编码"
              v-model.trim="tenantInfo.tenantCode">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="handleSave()">确 定</el-button>
        <el-button size="small" @click="isShowTenantDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import searchInput from 'public/search-input'
import TypeButton from '@/public/typeButton'
export default {
  components: {
    searchInput,
    TypeButton
  },
  data () {
    return {
      loading: false,
      isLoading: false,
      inputValue: '',
      page: 1,
      pageSize: 10,
      total: 0,
      tenantList: [],
      // 新增编辑租户
      isShowTenantDialog: false,
      mode: 'create',
      tenantInfo: {
        tenantName: '',
        tenantCode: ''
      },
      tenantRules: {
        tenantName: [
          { required: true, message: '请输入团队（企业）名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 添加租户
    addTenant () {
      this.mode = 'create'
      this.isShowTenantDialog = true
    },
    // 修改租户
    handleEdit (info) {
      this.mode = 'edit'
      this.tenantInfo = info
      this.isShowTenantDialog = true
    },
    // 点击保存
    handleSave () {
      this.$refs.tenantRef.validate((valid) => {
        if (valid) {
          switch (this.mode) {
            case 'create':
              this.saveAddTenant()
              break
            case 'edit':
              this.saveEditTenant()
              break
          }
        }
      })
    },
    // 保存添加
    saveAddTenant () {
      if (this.isLoading) {
        return
      }
      this.isLoading = true
      let url = `${this.SERVICE_TENANT}`
      let params = {
        tenantName: this.tenantInfo.tenantName,
        tenantCode: this.tenantInfo.tenantCode
      }
      this.posts(url, params).then(res => {
        this.isLoading = false
        if (res.data.code === 200) {
          this.showSucc(res.data.message)
          this.isShowTenantDialog = false
          this.fetchTenantList()
        }
      }).catch(err => {
        this.isLoading = false
        this.handleError(err)
      })
    },
    // 保存修改
    saveEditTenant () {
      if (this.isLoading) {
        return
      }
      this.isLoading = true
      let url = `${this.SERVICE_TENANT}/${this.tenantInfo.tenantId}`
      let params = {}
      params = Object.assign(params, this.tenantInfo)
      this.posts(url, params).then(res => {
        this.isLoading = false
        if (res.data.code === 200) {
          this.showSucc(res.data.message)
          this.isShowTenantDialog = false
          this.fetchTenantList()
        }
      }).catch(err => {
        this.isLoading = false
        this.handleError(err)
      })
    },
    clearTenantFields () {
      this.tenantInfo = {
        tenantName: '',
        tenantCode: ''
      }
    },
    // 删除
    handleDelete (info) {
      this.$confirm('确认删除该租户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.isLoading) {
          return
        }
        this.isLoading = true
        let url = `${this.SERVICE_TENANT}/invalid/${info.tenantId}`
        this.posts(url).then(res => {
          this.isLoading = false
          if (res.data.code === 200) {
            this.showSucc(res.data.message)
            this.fetchTenantList()
          }
        }).catch(e => {
          this.isLoading = false
          this.handleError(e)
        })
      }).catch(e => {
        this.$message({
          type: 'info',
          message: '操作已取消'
        })
      })
    },
    // 禁用/启用
    toggleUse (info) {
      let tip = info.isEnabled ? '确定禁用该租户吗？' : '确定启用该租户吗？'
      this.$confirm(tip, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.isLoading) {
          return
        }
        this.isLoading = true
        let url = ''
        if (info.isEnabled) {
          url = `${this.SERVICE_TENANT}/enabled/${info.tenantId}?isEnabled=false`
        } else {
          url = `${this.SERVICE_TENANT}/enabled/${info.tenantId}?isEnabled=true`
        }
        this.posts(url).then(res => {
          this.isLoading = false
          if (res.data.code === 200) {
            this.showSucc(res.data.message)
            this.fetchTenantList()
          }
        }).catch(e => {
          this.isLoading = false
          this.handleError(e)
        })
      }).catch(e => {
        this.$message({
          type: 'info',
          message: '操作已取消'
        })
      })
    },
    fetchTenantList () {
      this.loading = true
      let param = {
        keyword: this.inputValue || null,
        currentPage: this.page,
        pageSize: this.pageSize
      }
      let url = `${this.SERVICE_TENANT}/list`
      this.get(url, param).then(res => {
        this.loading = false
        if (res.data.code === 200) {
          let data = res.data.data
          if (data && data.list && data.list.length) {
            this.total = +data.total
            this.tenantList = data.list
          } else {
            this.tenantList = []
          }
        }
      }).catch(e => {
        this.loading = false
        this.handleError(e)
      })
    },
    handleNameSearch (value) {
      this.inputValue = value
      this.page = 1
      this.fetchTenantList()
    },
    handleSizeChange (val) {
      this.page = 1
      this.pageSize = val
      this.fetchTenantList()
    },
    handleCurrentChange (val) {
      this.page = val
      this.fetchTenantList()
    }
  },
  created () {
    this.fetchTenantList()
  }
}
</script>
<style lang="stylus" scoped>
.tenant-wrapper
  width 100%
  height 100%
  .tenant-body
    width 100%
    min-height 100%
    font-size 12px
    overflow-y auto
    background #f2f2f6
    padded_box(border-box, 6px)
    border-radius 6px
    .tenant-top
      between()
      width 100%
      background #fff
      padded_box(border-box, 15px 20px)
      border-radius 6px
      margin-bottom 6px
      .top_left
        >>> .el-input
          width 132px
          height 30px
          line-height 30px
        >>> .el-input__inner
          width 100%
          height 100%
          line-height 30px
        >>> .el-date-editor
          height 30px
          width 200px
        >>> .el-select .el-input__icon
          line-height 30px
        .left-label
          font-size: 12px;
          color: #5E5E66;
          margin-right 16px
        .left1
          font-size 0
          .search-input
            width 100%
        .left2
          margin 0 6px
        .chaxun
          color #3496FF
          cursor pointer
          font-size 12px
        .reset
          color #22242F
          cursor pointer
          font-size 12px
          margin-left 13px
      .right1
        flex .5
        right1()
        font-size 0
        >>> .el-input
          width 281px
    .table-wrapper
      background: #fff;
      box-sizing: border-box;
      padded_box(border-box, 15px 20px);
      border-radius: 6px;
      .status-wrapper
        display flex
        align-items center
        .icon
          width 24px
          height 24px
          background-repeat no-repeat
          background-position center
          background-size 100%
          margin-right 6px
          &.draft
            background-image url('~assets/img/enterprise/ic_draft@2x.png')
          &.complete
            background-image url('~assets/img/enterprise/icon_complete@2x.png')
            background-size 18px
        .text
          font-size: 14px;
          color: #888B9C;
      .caozuo
        display inline-block
        color #3496FF
        font-size 12px
        cursor pointer
        &.delete
          color #FA376C
        &.stop
          color #FF7E40
      .caozuo + .caozuo
        margin-left 20px
.tenant-info-wrapper
  >>> .el-dialog
    min-width 500px
</style>
